package com.evaluation.config;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import lombok.extern.slf4j.Slf4j;

@Slf4j
///@WebListener //需要打开 @ServletComponentScan
public class UserSessionListener implements HttpSessionListener {

	private static Map<String, String> onlineUsers = new HashMap<>();
	
	public static Map<String, String> getOnlineUsers() {
		return onlineUsers;
	}
	
	public static synchronized void setOnlineUser( String userId ) {
		onlineUsers.putIfAbsent(userId, DateUtil.now());
	}
	
	@Override
    public void sessionCreated(HttpSessionEvent se) {
		log.info( "{}", onlineUsers );
		log.info("进入Session创建事件,当前在线用户数：{}", onlineUsers.size());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		
		Object userId = se.getSession().getAttribute("userId");
		if( userId == null ) {
			return;
		}
		
		onlineUsers.remove( userId );
		
		log.info( "{}", onlineUsers );
		
		log.info("进入Session销毁事件,当前在线用户数：{}", onlineUsers.size() );
	}

}
